package net.cl.db;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.cl.db.core.BaseDao;
import net.cl.db.core.DBExecutorImpl;
import net.cl.db.ds.BasicDataSource;
import net.cl.utils.PathUtil;

/**
 * DB工厂
 * 
 * @author caol64@gmail.com
 */
public class DBFactory {

	private static final Log log = LogFactory.getLog(DBFactory.class);

	public static DBExecutor getDBExecutor(DataSource ds) throws DBException {
		DBExecutorImpl executor = new DBExecutorImpl(ds);
		// executor.setDialect(DBTools.guessDialect(ds));
		return executor;
	}

	public static BaseDao getDao(DataSource ds) throws DBException {
		return new BaseDao(getDBExecutor(ds));
	}

	public static void loadExternalDriver(String path) {
		try {
			PathUtil.addToClassPath(new File(path));
		} catch (IOException e) {
			log.error("can not load driver from '" + path + "', attempt to load from classpath", e);
		}
	}

	public static void close(BasicDataSource ds) {
		try {
			ds.close();
			log.debug("dataSource closed.");
		} catch (SQLException e) {
			log.error("dataSource closed error.", e);
		}
	}

}